package com.ybwh.springboot2;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * A controller for handling retrieval of version information
 */
@RestController
@RequestMapping("/")
public class VersionController {

    @RequestMapping(value = "/version", method= GET)
    public String versionInformation() {
        return readGitProperties();
    }

    /**
     * @return A String containing the contents of the git.properties file
     *         as generated by the Maven build
     */
    private String readGitProperties() {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("git.properties");
        try {
            return readFromInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return "Version information could not be retrieved";
        }
    }

    /**
     * Read an input stream and convert it into a string
     * @param inputStream The input stream
     * @return The converted input stream as a String
     * @throws IOException When an error occurs reading the input stream
     */
    private String readFromInputStream(InputStream inputStream)
            throws IOException {
        StringBuilder resultStringBuilder = new StringBuilder();
        try (BufferedReader br
                     = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line).append("\n");
            }
        }
        return resultStringBuilder.toString();
    }

}
